module.exports = class extends think.kms.admin {
  constructor(ctx) {
    super(ctx);
    this.tactive = 'user';
  }

  async indexAction() {
    const list = await this.model('auth_role').order('id ASC').select();
    this.assign({
      'title': '系统权限管理',
      "list": list
    })
    return this.display();
  }

  async indexAjaxAction() {
    const list = await this.model('auth_role').order('id ASC').select();
    return this.json(list);
  }

  /**
   * 添加角色
   */
  async addAction() {
    if (this.isPost) {
      const data = this.post();
      data.create_at = Date.now();
      let result = await this.model('auth_role').add(data)
      if (result) {
        return this.success('添加成功！');
      } else {
        return this.fail('添加失败');
      }
    }
    return this.display('admin/auth_form')
  }

  /**
   * 编辑角色
   */
  async editAction() {
    if (this.isPost) {
      const data = this.post();
      let result = await this.model('auth_role').where({id: data.id}).update(data)
      if (result) {
        return this.success('修改成功！');
      } else {
        return this.fail('修改失败');
      }
    }
    const id = this.get().id;
    const role = await this.model('auth_role').where({id: id}).find();
    think.logger.debug(role)
    this.assign({
      id: role.id,
      desc: role.desc,
      description: role.description
    })
    return this.display('admin/auth_form')
  }

  /**
   * 删除角色
   */
  async delAction() {
    console.log(this.post())
    const ids = this.post().id.split(',');
    let result = await this.model('auth_role').where({id: ids}).delete();
    think.logger.debug(result);
    if (result) {
      return this.success('删除成功！');
    } else {
      return this.fail('删除失败');
    }
  }

  /**
   * 禁用角色
   */
  async forbidAction() {
    const ids = this.post().id.split(',');
    const status = this.post().value;
    let result = await this.model('auth_role').where({id: ids}).update({status});
    if (result) {
      return this.success('操作成功！');
    } else {
      return this.fail('操作失败');
    }
  }
  
  /**
   * 启用角色
   */
  async resumeAction() {
    const ids = this.post().id.split(',');
    const status = this.post().value;
    let result = await this.model('auth_role').where({id: ids}).update({status});
    if (result) {
      return this.success('操作成功！');
    } else {
      return this.fail('操作失败');
    }
  }

  async applyAction() {
    this.assign({
      id: this.get('id')
    })
    return this.display();
  }

  async getnodeAction() {
    if (this.get('action') === 'getNode') {
      const where = {};
      where.status = ['>', '-1']
      if (!think.config('setup.DEVELOP_MODE')) {
        where.is_dev = 0;
      }
      const menu = await this.model('menu').where(where).order('sort asc').select();
      let node = arr_to_tree(menu, 0)
      return this.success(node)
    }
  }
}